package pl.lsierant.j2me.bipacz.intervaltimer;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

import pl.lsierant.j2me.bipacz.persistent.DeserializationHelper;
import pl.lsierant.j2me.bipacz.persistent.IPersistent;
import pl.lsierant.j2me.bipacz.persistent.PersistentObjectType;
import pl.lsierant.j2me.bipacz.persistent.SerializationHelper;
import pl.lsierant.j2me.bipacz.util.Util;

/**
 * Interval timer definition. Contains list of single interval definitions.
 */
public class IntervalTimerDef implements IPersistent {
    private String name;
    private Vector intervals;
    // how many times this timer repeats interval schedule; default repeat
    // indefinitely
    private int repeat = Integer.MAX_VALUE;

    public IntervalTimerDef() {
    }

    public IntervalTimerDef(String name, Interval[] intervals, int repeat) {
        super();
        this.intervals = Util.arrayToVector(intervals);
        this.name = name;
        this.repeat = repeat;
    }

    public IntervalTimerDef(String name, Interval[] intervals) {
        super();
        this.name = name;
        this.intervals = Util.arrayToVector(intervals);
    }

    public IntervalTimerDef(Interval[] intervals) {
        super();
        this.intervals = Util.arrayToVector(intervals);
    }

    public Interval getInterval(int n) {
        if (n >= intervals.size()) {
            throw new IllegalArgumentException(n + "");
        }
        return (Interval) intervals.elementAt(n);
    }

    public int size() {
        return intervals.size();
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getRepeat() {
        return repeat;
    }

    public void setRepeat(int repeat) {
        this.repeat = repeat;
    }

    public int getPersistentObjectType() {
        return PersistentObjectType.INTERVAL_TIMER_DEF;
    }

    public void initialize(DataInputStream serializedData) throws IOException {
        DeserializationHelper helper = new DeserializationHelper(serializedData);
        name = ((String) helper.readObject());
        intervals = ((Vector) helper.readObject());
        repeat = ((Integer) helper.readObject()).intValue();
    }

    public void serialize(DataOutputStream out) throws IOException {

        SerializationHelper helper = new SerializationHelper(out, this, 0);
        helper.addField(name);
        helper.addVector(intervals);
        helper.addField(repeat);
    }

    public String toString() {
        return "IntervalTimerDef [intervals=" + Util.vectorToString(intervals) + ", name=" + name
                + ", repeat=" + repeat + "]";
    }

}
